//
//  TRRequestTool.m
//  iOSBaseFramework
//
//  Created by user on 2020/6/16.
//  Copyright © 2020 com.taylor. All rights reserved.
//

#import "TRRequestTool.h"
#import "TRRequestManager.h"
#import "UIImage+tool.h"
#import "AFNetworking/AFNetworking/AFNetworkReachabilityManager.h"


#import <objc/runtime.h>

@implementation TRRequestTool

+ (void)monitoringNetworkState:(void (^)(NSInteger))block {
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager startMonitoring];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
            {
                NSLog(@"[ 网络状态切换 ] -- 未知网络");
            }
                break;
            case AFNetworkReachabilityStatusNotReachable:
            {
                NSLog(@"[ 网络状态切换 ] -- 无法联网 ");
            }
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
            {
                NSLog(@"[ 网络状态切换 ] -- WIFI网络");
            }
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
            {
                NSLog(@"[ 网络状态切换 ] -- 手机移动网络2G/3G/4G");
            }
                break;
            default:
                break;
        }
        
        block(status);
    }];
}


- (NSString *) baseUrl {
    return [TRRequestManager shareHTTPManage].baseURL.absoluteString;
}


+ (instancetype)shareManager{
    static TRRequestTool *shareManager = nil;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        shareManager = [[TRRequestTool alloc] init];
    });
    return shareManager;
}

- (void)sendRequestWithAPI:(NSString *)requestAPI withVC:(id)vc withParams:(NSDictionary *)params withClass:(NSString *)className responseBlock:(RequestResponse)response
{
    NSLog(@"sendRequestWithAPI:");
    
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    [TRRequestManager shareHTTPManage].requestSerializer.stringEncoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    [TRRequestManager shareHTTPManage].requestSerializer.HTTPShouldHandleCookies = NO;
    NSString *baseUrl = [TRRequestManager shareHTTPManage].baseURL.absoluteString;
    
    NSLog(@"\nRequest =====> URL:%@%@\nparams:%@", baseUrl,requestAPI,params);
    [[TRRequestManager shareHTTPManage] POST:requestAPI parameters:params headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"\nResponse=====>URL:%@%@\nresult:%@",baseUrl,requestAPI, [responseObject description]);
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        if (className) {
            Class class = NSClassFromString(className);
            NSObject *responseModel = [[class alloc] init];
            response(responseModel, [[responseObject valueForKey:@"code"] isEqualToString:@"0"] ? NO:YES, [responseObject valueForKey:@"message"], [[responseObject valueForKey:@"code"] integerValue]);
        } else {
            response(responseObject,[[responseObject valueForKey:@"code"] isEqualToString:@"0"] ? NO:YES,[responseObject valueForKey:@"message"],[[responseObject valueForKey:@"code"] integerValue]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        if (error.code == -1009) {
            response(nil, YES, @"互联网的连接似乎已经断开",error.code);
        } else if (error.code == -1001){
            response(nil, YES, @"请求超时", error.code);
        } else if(error.code == -1011){
            response(nil,YES,@"不支持该响应类型",error.code);
        } else {
            response(nil,YES,@"服务器需要休息片刻",error.code);
        }
    }];
}


-(void)createDownloadTaskWithURL:(NSString *)url
                    withFileName:(NSString *)fileName
                            Task:(DownloadTask)downloadTask
                        Progress:(TaskProgress)progress
                          Result:(TaskResult)result {
    NSString *taskName = @"download";
    dispatch_queue_t queue = dispatch_queue_create([taskName cStringUsingEncoding:(NSUTF8StringEncoding)], DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(queue, ^{
        NSURL *requestURL = [NSURL URLWithString:url];
        NSURLRequest *request = [NSURLRequest requestWithURL:requestURL];
        NSURLSessionDownloadTask *task = [[TRRequestManager shareTaskManage] downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
            dispatch_async(dispatch_get_main_queue(), ^{
                progress(downloadProgress.fractionCompleted, fileName);
            });
        } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
            NSString *cachaPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
            NSString *path = [cachaPath stringByAppendingPathComponent:fileName];
            NSURL *fileURL = [NSURL fileURLWithPath:path];
            return fileURL;
        } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
            BOOL isError = NO;
            if (error) {
                isError = YES;
                NSLog(@"error:%@", [error description]);
            } else {
                NSLog(@"%@下载完成", fileName);
            }
            result(response, isError);
        }];
        [task resume];
        task.taskDescription = fileName;
        downloadTask(task);
    });
}

- (void)uploadImageWithUrl:(NSString *)url WithImage:(id)image Params:(NSDictionary *)params Task:(id)uploadTask Progress:(TaskProgress)progress Result:(TaskResult)result
{
//
    NSString *formatAPI = [NSString stringWithFormat:@"app/%@.htm?imgType=%ld",url,[[params objectForKey:@"imgType"] integerValue]];
        NSLog(@"\nRequest======>URL:%@%@", [TRRequestManager shareHTTPManage].baseURL.absoluteString, formatAPI);
    NSData *data = [UIImage smallTheImageBackData:image];
    
    NSString *taskName = @"uploadImage";
    dispatch_queue_t queue = dispatch_queue_create([taskName cStringUsingEncoding:NSUTF8StringEncoding], DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(queue, ^{
        __block NSURLSessionDataTask *task = [[TRRequestManager shareHTTPManage] POST:formatAPI parameters:params headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            [formData appendPartWithFileData:data name:@"file" fileName:@"file.png" mimeType:@"image/png"];
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            dispatch_async(dispatch_get_main_queue(), ^{
                progress(uploadProgress.fractionCompleted, task.taskDescription);
            });
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSInteger  code = [[responseObject objectForKey:@"code"] integerValue];
            result(responseObject, code==0?NO:YES);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            result(error, YES);
        }];
    });
}
    
@end
